-module(control).
-export([basic/0, start_two/0, start/0, stop/2, start/2, stop/0, cells_pids/1, interface/1, show_cell/1, set_field/3]).
-include("cell_records.hrl").

%% starts control and connector processes
basic() ->
  register(control, spawn(control, interface, [[]])),
  props:init(),
  connector:init().

start_two() ->
  control:basic(),
  start:init_two().

start() ->
  control:start(3, 3).

start(Width, Height) ->
  control:basic(),
  start:init(Width, Height).

init() ->
  props ! {get, size, self()},
  receive
    stop -> exit("stopped while waiting for position");
    {size, X, Y} ->
      start:init(X, Y)
  end.

interface(First) ->
  receive
    {find, X, Y, Pid} ->
      First ! {multicast, all, -1, {echo, X, Y, Pid}},
      interface(First);
    print ->
      First ! {multicast, all, -1, print_veg},
      interface(First);
    print_all ->
      io:format("interface: ~p~n", [First]),
      interface(First);
    {all, Msg} ->
      First ! {multicast, all, -1, Msg},
      interface(First);
    {first, Pid} ->
      interface(Pid);
    init ->
      init(),
      interface(First);
    play ->
      First ! {multicast, all, -1, play},
      props ! play,
      interface(First);
    pause ->
      First ! {multicast, all, -1, pause},
      props ! pause,
      interface(First);
    stop ->
      stop_all(First),
      props ! stop,
      interface(First);
    exit ->
      stop_all(First),
      props ! exit,
      ok;
    {return_first, Pid} ->
      Pid ! First,
      interface(First)
  end.

stop() ->
  connector ! exit,
  control ! exit.

stop(From, To) when From =< To ->
  erlang:pid(0,From,0) ! stop,
  stop(From + 1, To);
stop(_From, _To) ->
  ok.

cells_pids(Pid) ->
  control ! {return_list, Pid}.

stop_all([]) ->
  ok;
stop_all(Pid) ->
  Pid ! {multicast, all, -1, stop}.


show_cell(Pid) ->
  Pid ! print_all.

set_field(Pid, Field, Value) ->
  Pid ! {set, Field, Value}.
